<template>
  <el-dialog 
    v-model="dialogVisible" 
    title="DeadSplit Setting" 
    width="60%"
    @open="resetForm"
    ref="diagRef"
    :before-close="handleClose"
  >
    <!-- 游戏设置部分 -->
     <el-scrollbar max-height="300px" >
    <el-collapse v-model="activeNames" class="mb-4" style="width: 98%;">
      <el-collapse-item name="gameSettings" title="游戏设置（全部为必填）">
        <el-form 
          ref="gameFormRef" 
          :model="gameForm" 
          :rules="gameRules" 
          label-width="120px"
          class="mt-2"
          style="padding-right: 20px;"
          
        >
          <!-- 游戏标题 -->
          <el-form-item label="Fangame title" prop="title">
            <el-input 
              v-model="gameForm.title" 
              placeholder="请输入游戏标题"
              clearable
            ></el-input>
            <div 

              :style="{ fontSize: '12px',lineHeight: '12px', marginTop: '8px',color:'#909399',fontWeight:'500'}"
            >
              游戏名在项目文件夹必须是唯一，否则会覆盖
          </div>
          </el-form-item>
          
          <el-form-item label="Room address" prop="roomAddress">
            <el-input 
              v-model="gameForm.roomAddress" 
              placeholder="Room address"
              clearable
            ></el-input>
            <el-link 
              type="info" 
              href="https://www.cheatengine.org/" 
              target="_blank"
              :style="{ fontSize: '12px',lineHeight: '12px', marginTop: '8px'}"
            >
              地址和房间id需要使用Cheat Engine，请访问官网获取
            </el-link>
          </el-form-item>
          
          <!-- 存档位置 -->
          <el-form-item label="DeathTimefile" prop="dtFile">
            <el-input 
              v-model="gameForm.dtFile" 
              placeholder="select save file"
              readonly
              style="width: 65%;margin-right: 10px;"
              class="mb-2"
            >
           <!--  <template #append>
              <el-icon class="reset-button" @click="gameForm.saveFile='default'"><Refresh/></el-icon>
            </template> -->
            </el-input>
            <el-button 
              type="primary" 
              @click="selectDtFile"
            >
            <el-icon class="el-icon--left"><Upload/></el-icon>
              select
            </el-button>
          </el-form-item>

        </el-form>
      </el-collapse-item>
      
      <!-- Boss设置部分 -->
      <el-collapse-item name="bossSettings" title="当前Boss">
        <div class="boss-settings-container">
          <!-- Boss菜单选择 -->
          <el-scrollbar  wrapStyle="display: flex;"><el-menu 
            ref="menuRef"
            mode="horizontal" 
            :default-active="currentBossIndex.toString()"
            @select="handleBossSelect"
            class="boss-menu"
            overflow="hidden"
            :ellipsis="false"
          >
          
            <el-menu-item 
              v-for="(boss, index) in bossSettings" 
              :key="index" 
              :index="index.toString()"
              class="boss-menu-item"
            >
              <span class="boss-name">
                {{ boss.name || `Boss #${index + 1}` }}
              </span>
              <el-button 
                type="text"  
                size="small" 
                class="delete-btn"
                @click.stop="removeBoss(index)"
                :disabled="bossSettings.length <= 1"
                
              ><el-icon style="display: flex;justify-content: center;margin: 0;"><Delete/></el-icon></el-button>
            </el-menu-item>
            
            
            <el-menu-item 
              index="add" 
              class="add-boss-item"
              @click="addBoss"
            >
              <el-icon><Plus/></el-icon>
              <span>添加Boss</span>
            </el-menu-item>
          </el-menu></el-scrollbar>
        
          <!-- 当前Boss设置表单 -->
          <el-form 
            ref="bossFormRef" 
            :model="currentBoss" 
            :rules="bossRules"
            label-width="120px"
            class="mt-2"
            style="padding-right: 20px;"
          >
            <!-- Boss名称 -->
            <el-form-item label="Boss name" style="margin-top: 20px;">
              <el-input 
                v-model="currentBoss.name" 
                placeholder="Boss名称"
                clearable
              ></el-input>
            </el-form-item>
            
            <!-- Preroom id -->
            <el-form-item label="Preroom id">
              <el-input 
                v-model="currentBoss.preroomId" 
                placeholder="请输入preroom id（选填）"
                clearable
              ></el-input>
            </el-form-item>
            
            <el-form-item label="Bgm length (s)">
              <el-input 
                v-model="currentBoss.bgmLength" 
                placeholder="default:-10000"
                clearable
              ></el-input>
            </el-form-item>
            
            <!-- Start Trigger -->
            <el-form-item label="Start trigger" prop="startTriggers">
              <el-select
                v-model="currentBoss.startTriggers"
                multiple
                placeholder="请选择触发条件"
                @change="handleTriggerChange($event,'start')"
                
              >
                <el-option
                  label="restart"
                  value="restart"
                ></el-option>
                <el-option
                  label="房间变换"
                  value="roomChange"
                ></el-option>
                <el-option
                  label="shoot save"
                  value="shootSave"
                ></el-option>
              </el-select>

               <!-- 房间变换对应的房间ID输入 -->
              <el-input v-if="currentBoss.startTriggers.includes('roomChange')"
                v-model="currentBoss.startRoomID"
                placeholder="请输入房间变换的房间ID"
                class="mt-2"
                clearable
              ></el-input>


            <!-- shoot save对应的roomid输入 -->
              <el-input
                v-if="currentBoss.startTriggers.includes('shootSave')"
                v-model="currentBoss.startSaveRoomId"
                placeholder="请输入shoot save的roomid"
                class="mt-2"
                clearable
              ></el-input>
            </el-form-item>

             

            <!-- End Trigger -->
            <el-form-item label="End trigger" prop="endTrigger">
              <el-select
              class="multi-select-inline"
                clearable
                v-model="currentBoss.endTrigger"
                placeholder="请选择触发条件"
                @change="handleTriggerChange($event,'end')"
              ><el-option
                  label="Time out"
                  value="timeOut"
                />
                <el-option
                  label="房间变换"
                  value="roomChange"
                ></el-option>
                <el-option
                  label="shoot save"
                  value="shootSave"
                ></el-option>
              </el-select>
              <!-- 房间变换对应的房间ID输入 -->
              <el-input
                v-if="currentBoss.endTrigger=='roomChange'"
                v-model="currentBoss.endRoomID"
                placeholder="请输入房间变换的房间ID"
                class="mt-2"
                clearable
              ></el-input>
              
              <!-- shoot save对应的roomid输入 -->
              <el-input
                v-if="currentBoss.endTrigger=='shootSave'"
                v-model="currentBoss.endSaveRoomId"
                placeholder="请输入shoot save的roomid"
                class="mt-2"
                clearable
              ></el-input>
            </el-form-item>
            
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
    </el-scrollbar>
    <!-- 对话框底部按钮 -->
    <template #footer>
      <el-button @click="diagRef.handleClose">取消</el-button>
      <el-button type="primary" @click="saveSettings_before">保存设置</el-button>
    </template>
    
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch,getCurrentInstance } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import { Plus, Minus, Upload, Delete,Refresh } from '@element-plus/icons-vue';
import {open} from '@tauri-apps/plugin-dialog';
import { ca } from 'element-plus/es/locales.mjs';

const emit=defineEmits(['updateBossData']);
// 对话框显示状态
const diagRef=ref(false);
const dialogVisible = ref(false);
const $global = getCurrentInstance().appContext.config.globalProperties;
// 折叠面板状态
const activeNames = ref(['gameSettings', 'bossSettings']);

// 游戏设置表单数据
const gameForm = reactive({
  title: '',
  roomAddress: '',
  dtFile: '',
  currentBoss:0
});
const validateTrigger = (rule, value, callback) => {
  //console.log(rule)
  if (rule.field === 'startTriggers') {
    if (currentBoss.value.startTriggers.includes('shootSave') && currentBoss.value.startSaveRoomId === '') {
      callback(new Error('Please input roomid where savepoint in'));
    }
    if (currentBoss.value.startTriggers.includes('roomChange') && currentBoss.value.startRoomID === '') {
      callback(new Error('Please input the boss roomid'));
    }
  }
  else{
    if (currentBoss.value.endTrigger==='shootSave' && currentBoss.value.endSaveRoomId === '') {
      callback(new Error('Please input roomid where savepoint in'));
    }
    if (currentBoss.value.endTrigger==='roomChange' && currentBoss.value.endRoomID === '') {
      callback(new Error('Please input the boss roomid'));
    }
  }
  callback();
}
// 游戏设置表单验证规则
const gameRules = reactive({
  title: [
    { required: true, message: '请输入游戏标题', trigger: 'blur' }
  ],
  roomAddress: [
    { required: true, message: '请输入Room Address', trigger: 'blur' }
    
  ],
  dtFile: [
    { required: true, message: '请选择存档文件', trigger: 'blur' }
  ]
});

const bossRules = reactive({
  startTriggers: [
    { required: true, message: 'Please select at least one trigger', trigger: 'blur' },
    {validator: validateTrigger,trigger: 'blur'}
  ],
  endTrigger: [
    { required: true, message: 'Please select at least one trigger', trigger: 'blur' },
    
    {validator: validateTrigger,trigger: 'blur'}
  ]
});


// Boss设置数据(顺序为唯一键，不可改变顺序)
const bossSettings = reactive([
  {
    name: '',
    preroomId: '',
    startTriggers: [],
    startRoomID: '',
    startSaveRoomId: '',
    endTrigger:'',
    endRoomID: '',
    endSaveRoomId: '',
    bgmLength:0
  }
]);

// 当前选中的Boss索引
const currentBossIndex = ref(0);
const currentBoss = ref(bossSettings[0]);

// 表单引用
const gameFormRef = ref(null);
const bossFormRef = ref(null);
const menuRef=ref(null);


// 监听当前Boss索引变化，更新当前Boss数据
watch(currentBossIndex, (newVal) => {
  currentBoss.value = bossSettings[newVal];
  gameForm.currentBoss = newVal;
});

// 处理Boss选择
const handleBossSelect = (index) => {
  if (index!==currentBossIndex.value.toString())
  checkForm('boss').then((flag)=>{
    if(flag){
      if (index !== 'add') {
        currentBossIndex.value = parseInt(index);
      }
    }
    else{
      menuRef.value.updateActiveIndex(currentBossIndex.value.toString());
      ElMessage.error('请检查表单是否填写正确');
    }
  }).catch((err)=>{
    menuRef.value.updateActiveIndex(currentBossIndex.value.toString());
    ElMessage.error("错误："+err);
  })
  
};

// 添加新的Boss设置
const addBoss = () => {
  checkForm('boss').then((flag)=>{
    if(flag){
      bossSettings.push({
        name: '',
        preroomId: '',
        startTriggers: [],
        startRoomID: '',
        startSaveRoomId: '',
        endTrigger:'',
        endRoomID: '',
        endSaveRoomId: '',
      })
      currentBossIndex.value = bossSettings.length - 1;
      actionQueue.value.push({index:currentBossIndex.value,action:'add'});
    }
    else{
      //ElMessage.error('请检查表单是否填写正确');
      menuRef.value.updateActiveIndex(currentBossIndex.value.toString());
    }
}).catch((err)=>{
menuRef.value.updateActiveIndex(currentBossIndex.value.toString());
  
    ElMessage.error("错误："+err);
  })
  
  
};
const actionQueue=ref([]);
/* interface qItem{
  index:number,
  action:string
} */
// 删除指定索引的Boss
const removeBoss = (index) => {
  if (bossSettings.length <= 1) {
    ElMessage.warning('至少保留一个Boss配置');
    return;
  }
  ElMessageBox.confirm(
    'This boss will be deleted. If you do this, the attack of this boss will also be deleted after you save. Continue?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      try{
            // 如果删除的是当前选中的Boss，需要调整选中索引
        if (index === currentBossIndex.value) {
          // 如果是最后一个元素，选中前一个
          if (index === bossSettings.length - 1) {
            currentBossIndex.value = index - 1;
          } else {
            // 否则选中下一个
            currentBossIndex.value = index;
          }
        } else if (index < currentBossIndex.value) {
          // 如果删除的是当前选中之前的元素，调整索引
          currentBossIndex.value--;
        }
        
        bossSettings.splice(index, 1);
        actionQueue.value.push({index:index,action:'delete'});
      }catch(err){
        ElMessage.error('Deleted failed'+err);
      }
    })
  
};

// 处理触发条件变化
const handleTriggerChange = (values,type) => {
  // 如果移除了房间变换，清空对应的ID
  if (type=='start'){
  if (!values.includes('roomChange')) {
    currentBoss.value.startRoomID = '';
  }
  
  // 如果移除了shoot save，清空对应的ID
  if (!values.includes('shootSave')) {
    currentBoss.value.startSaveRoomId = '';
  }}
  else{
    if (!values){
      currentBoss.value.endTrigger=''
      currentBoss.value.endRoomID = '';
      currentBoss.value.endSaveRoomId = '';
    }
    else{if (!values.includes('roomChange')) {
    currentBoss.value.endRoomID = '';
  }
  
  // 如果移除了shoot save，清空对应的ID
  if (!values.includes('shootSave')) {
    currentBoss.value.endSaveRoomId = '';
  }}
  }
};

// 选择存档文件
const selectDtFile = async () => {
   const selected = await open({
    directory: false,
    multiple: false,
    title: '选择存档'
  });
  console.log(selected);
  if (selected) {
    gameForm.dtFile = Array.isArray(selected) ? selected[0] : selected;
  }
};
/* // 选择导出路径
const selectExportPath = async () => {
  const selected = await open({
    directory: true,
    multiple: false,
    title: '选择导出路径'
  });
  
  if (selected) {
    settings.value.exportPath = Array.isArray(selected) ? selected[0] : selected;
  }
}; */

const checkForm=async(...arg)=>{
    // 验证游戏设置表单
let errFlag1=false,errFlag2=false;
  

  const bossValid = await bossFormRef.value.validate().catch(err=>{
    errFlag2=true;
  })
if (arg[0] && arg[0]=='boss'){

    if (errFlag2){
      return false
    }
  }
  else{
    const gameValid = await gameFormRef.value.validate().catch(err=>{
      errFlag1=true;
    })
    if (errFlag1 || errFlag2){
    ElMessage.error('请检查表单是否填写正确');
    return false;
  }}
  return true
}
// 保存设置
const saveSettings_before = async () => {

  const flag=await checkForm();
  if (!flag) {
    
    return;
  } 

  emit('updateBossData');
  // 这里可以添加Boss表单的验证逻辑
};
//更新数据后完成后续操作
const saveSettings = () => {
  const settingsData = {
     ...gameForm ,
    bosses: [...bossSettings]
  };
  
  // 在实际应用中，这里会发送数据到后端或保存到本地存储
  //console.log('保存的设置:', settingsData);
  $global.$deadSplitData.value={...settingsData};
  //console.log(actionQueue.value)
  if  (actionQueue.value.length>0)
  for (let e of actionQueue.value){
    if (e.action=='delete')
      $global.$bossData.value.splice(e.index,1);
    else if (e.action=='add')
      $global.$bossData.value.push([]);
  }
  actionQueue.value=[];
  
  ElMessage.success('设置保存成功');
  
  dialogVisible.value = false;
}

function deepEqual(obj1, obj2) {
    // 检查是否是同一对象或值
    if (obj1 === obj2) {
        return true;
    }

    // 检查是否存在 null 或 undefined
    if (obj1 == null || obj2 == null) {
        return obj1 === obj2;
    }



    

    
    // 比较数组长度
    if (Array.isArray(obj1) && Array.isArray(obj2)) {
        if (obj1.length !== obj2.length) {
            return false;
        }
        for (let i = 0; i < obj1.length; i++) {
            if (!deepEqual(obj1[i], obj2[i])) {
                return false;
            }
        }
        return true;
    }

    // 获取对象的所有键
    const keys1 = Object.keys(obj1);
    const keys2 = Object.keys(obj2);

    // 比较键长度
    if (keys1.length !== keys2.length) {
        return false;
    }

    // 比较键和值
    for (let key of keys1) {
        if (!key in obj2) {
            return false;
        }
        if (!deepEqual(obj1[key], obj2[key])) {
            return false;
        }
    }

    return true;
}
const resetForm=()=>{
  gameFormRef.value.clearValidate()
  actionQueue.value=[];
  /* for(let i=0;i<$global.$bossData.value.length;i++){
    console.log($global.$deadSplitData.value.bosses[i],$global.$bossData.value[i])
  } */
  const {bosses,...res}=$global.$deadSplitData.value;
  const keys=Object.keys(gameForm);
  for (let key of keys){
    gameForm[key]=res[key];

  }
  
  bossSettings.splice(0,bossSettings.length);
  for (let i=0;i<$global.$deadSplitData.value.bosses.length;i++){
    bossSettings.push({
      ...$global.$deadSplitData.value.bosses[i],
      startTriggers: [...$global.$deadSplitData.value.bosses[i].startTriggers]
    });
  }
  currentBossIndex.value=$global.$deadSplitData.value.currentBoss;
  currentBoss.value=bossSettings[currentBossIndex.value]
  bossFormRef.value.clearValidate();
/*   for(let i=0;i<bossSettings.length;i++){
    console.log(gameForm,bossSettings[i])
  } */
}

// 关闭对话框处理
const handleClose = (done) => {
  //console.log('关闭对话框')
  //ElMessage.warning('设置未保存，确认关闭？');
  console.log(bossSettings)
  const settingsData = {
     ...gameForm ,
    bosses: [...bossSettings]
  };


 /*  console.log({...$global.$deadSplitData.value})
  console.log(settingsData)
  console.log(deepEqual({...$global.$deadSplitData.value},settingsData)) */
  if (!deepEqual($global.$deadSplitData.value,settingsData))
  ElMessageBox.confirm(
    '设置未保存，确认关闭？',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      done();
    })
    else done();
  }
// 暴露方法供外部控制对话框显示
defineExpose({
  open: () => {
    dialogVisible.value = true;
  },
  saveSettings
});
</script>

<style scoped>

:deep(.el-select__selection) {
  flex-wrap: nowrap; 

}
.boss-settings-container {
  padding: 10px 0;
}

.boss-menu {
  background-color: #f5f7fa;
  border-radius: 4px; 
  border: 1px solid #dcdfe6;
  min-width: 439px;
}

.boss-menu-item {
  position: relative;
  margin-left: 2px;
  margin-right: 1px;
  padding-right: 40px !important; /* 为删除按钮预留空间 */
  transition: all 0.2s;
}

.boss-menu-item:hover {
  background-color: rgba(64, 150, 255, 0.1);
}

.boss-name {
  margin-right: 10px;
}

.delete-btn {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #f56c6c;
  padding: 0;
  opacity: 0.7;
  transition: all 0.2s;

}

.delete-btn:hover {
  opacity: 1;
  background-color: rgba(245, 108, 108, 0.1);
}

.add-boss-item {
  background-color: #ecf5ff;
  color: #4096ff;
  margin-left: auto; /* 推到右侧 */
  transition: all 0.2s;
}

.add-boss-item:hover {
  background-color: #d9ecff;
  color: #1677ff;
}

.add-boss-item .el-icon {
  margin-right: 5px;
}
.reset-button:hover{
  color: #4096ff;
  border-color: #b3d8ff;
  cursor: pointer;
}
::v-deep .el-input-group__append{
  padding: 10px ;
}
::v-deep .el-input-group__append:hover{
  background-color: #dcdfe6;
  cursor: pointer;
}
::v-deep .el-input-group__append:active{
  background-color: #ecf5ff;
  cursor: pointer;
}
</style>
    